const configs = require('config');
import Iredis from '../plugs/Iredis'
import * as util from './util'
import axios from 'axios'
const api = {
  "wechatDomain":"https://api.weixin.qq.com",
  'access_token':'/cgi-bin/token?grant_type=client_credential',
  'jsTicket':'/cgi-bin/ticket/getticket',
  'unifiedorder':'https://api.mch.weixin.qq.com/pay/unifiedorder'
}
export default class Wechat {
  constructor(){
    this.fetchAccessToken();
  }
  async fetchAccessToken(){
    let token = await Iredis.getInstance().client.getAsync(configs.get('accessTokenKey'));
    if(!token){
      token =await this.updateAccessToken()
    }
    return token
  }
  async updateAccessToken(){
    const result = await axios.get(`${api.wechatDomain}${api.access_token}&appid=${configs.get('appID')}&secret=${configs.get('appSecret')}`);
    if(result.data.access_token){
      await Iredis.getInstance().client.setAsync(configs.get('accessTokenKey'),result.data.access_token,'EX',result.data.expires_in-2)
      return result.data.access_token
    }
    return result.data;
  }
  async fetchTicket(token){
    let ticket = await Iredis.getInstance().client.getAsync(configs.get('jsTicketKey'));
    if(!ticket){
      ticket =await this.updateTicket(token)
    }
    return ticket
  }
  async updateTicket(token){
    const result = await axios.get(`${api.wechatDomain}${api.jsTicket}?access_token=${token}&type=jsapi`)
    if(result.data.ticket){
      await Iredis.getInstance().client.setAsync(configs.get('jsTicketKey'),result.data.ticket,'EX',result.data.expires_in-2)
      return result.data.ticket
    }
  }
  sign(jsapi_ticket,url){
    const noncestr = util.createNoncestr();
    const timestamp = util.createTimestamp()
    const signature = util.createSignature({
      jsapi_ticket,
      noncestr,
      timestamp,
      url
    })
    return {
      noncestr,
      timestamp,
      signature
    }
  }
}